import { ref } from 'vue';
import api from '../api/api';
import { useAuthStore } from '../stores/authStore';

// 创建文章逻辑
export const useCreateArticle = () => {
  const loading = ref(false);
  const error = ref('');
  const successMessage = ref('');

  // 提交文章
  const createArticle = async (title, content, categoryId) => {
    loading.value = true;
    error.value = '';
    successMessage.value = '';

    const userId = useAuthStore().id;
    if (!userId) {
      error.value = '用户未登录或身份信息异常';
      return;
    }
  
    const processedContent = typeof content === 'string' ? content : JSON.stringify(content);

    const articleData = {
      title,
      content: processedContent,
      categoryId,
      userId,
    };

    try {
      const response = await api.post('/articles/auth', articleData);

      if (response.data.code === 1 && response.data.msg === 'success') {
        successMessage.value = response.data.data;
        return true;
      } else {
        error.value = '提交文章失败';
        return false;
      }
    } catch (err) {
      console.error('请求出错:', err);
      error.value = '网络错误，请重试';
      return false;
    } finally {
      loading.value = false;
    }
  };

  return { 
    loading, 
    error, 
    successMessage, 
    createArticle 
  };
};